(*
  Copyright (c) 2009 Barry Schwartz

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*)

(*-----------------------------------------------------------------------*)

open Gmp
open Pycaml
  
type num = Q.t

let description = "GNU MP"
let module_name = "gmp"

(*-----------------------------------------------------------------------*)

let num_of_int x = Q.from_ints x 1
let num_of_ints x y = Q.from_ints x y
let float_of_num = Q.to_float
let string_of_num = Q.to_string
let num_zero = Q.zero
let num_one = num_of_int 1
let num_minus_one = num_of_int (-1)
let num_two = num_of_int 2
let num_three = num_of_int 3
let num_ten = num_of_int 10
let add_num = Q.add
let minus_num = Q.neg
let sub_num = Q.sub
let mult_num = Q.mul
let div_num = Q.div
let sign_num = Q.sgn
let compare_num = Q.compare

let square_num x = mult_num x x

let is_integer_num x = Z.equal_int (Q.get_den x) 1
  
let power_num_int x exp =
  if exp = 0 then
    num_one
  else if exp > 0 then
    Q.from_zs (Z.pow_ui (Q.get_num x) exp) (Z.pow_ui (Q.get_den x) exp)
  else
    Q.from_zs (Z.pow_ui (Q.get_den x) (- exp))
      (Z.pow_ui (Q.get_num x) (- exp))
  
let power_num x y =
  if is_integer_num y then
    power_num_int x (Z.to_int (Q.get_num y))
  else
    invalid_arg "power_num"
  
let abs_num x = match Q.sgn x with | (-1) -> Q.neg x | _ -> x
let succ_num x = Q.add x num_one
let pred_num x = Q.sub x num_one
let incr_num x = x := succ_num !x
let decr_num x = x := pred_num !x
let floor_num x = Q.from_z (Z.fdiv_q (Q.get_num x) (Q.get_den x))
let ceiling_num x = Q.from_z (Z.cdiv_q (Q.get_num x) (Q.get_den x))
  
let integer_num x =
  let n = Q.get_num x in
  let d = Q.get_den x in
  let (q, r) = Z.tdiv_qr n d in
    if (Z.cmp_si n 0) < 0 then
      if (Z.add d r) < r then
        Q.from_z (Z.sub_ui q 1)
      else
        Q.from_z q
    else if (Z.sub d r) < r then
      Q.from_z (Z.add_ui q 1)
    else
      Q.from_z q

let round_num x =
  let n = Q.get_num x in
  let d = Q.get_den x in
  let (q, r) = Z.tdiv_qr n d in
    if (Z.cmp_si n 0) < 0 then
      if (Z.add d r) <= r then
        Q.from_z (Z.sub_ui q 1)
      else
        Q.from_z q
    else if (Z.sub d r) <= r then
      Q.from_z (Z.add_ui q 1)
    else
      Q.from_z q
  
let quo_num x y = floor_num (div_num x y)
let mod_num x y = sub_num x (mult_num y (quo_num x y))
let eq_num x y = (Q.cmp x y) = 0
let lt_num x y = (Q.cmp x y) < 0
let le_num x y = (Q.cmp x y) <= 0
let gt_num x y = (Q.cmp x y) > 0
let ge_num x y = (Q.cmp x y) >= 0
let max_num x y = if lt_num x y then y else x
let min_num x y = if gt_num x y then y else x
  
let land_num x y =
  if (is_integer_num x) && (is_integer_num y) then
    Q.from_z (Z.band (Q.get_num x) (Q.get_num y))
  else
    invalid_arg "land_num"
  
let lor_num x y =
  if (is_integer_num x) && (is_integer_num y) then
    Q.from_z (Z.bior (Q.get_num x) (Q.get_num y))
  else
    invalid_arg "lor_num"
  
let lxor_num x y =
  if (is_integer_num x) && (is_integer_num y) then
    Q.from_z (Z.bxor (Q.get_num x) (Q.get_num y))
  else
    invalid_arg "lxor_num"
  
let lneg_num x =
  if is_integer_num x then
    Q.from_z (Z.bcom (Q.get_num x))
  else
    invalid_arg "lneg_num"
  
let num_of_string s =
  try
    let n = String.index s '/' in
      Q.from_zs (Z.from_string (String.sub s 0 n))
        (Z.from_string (String.sub s (n + 1) (((String.length s) - n) - 1)))
  with | Not_found -> Q.from_z (Z.from_string s)
  
let int_of_num x =
  if is_integer_num x then
    Z.to_int (Q.get_num x)
  else
    failwith "integer argument required"
  
let num_of_float x =
  let (f, n) = frexp x in
  let factor = power_num_int num_two n in
  let str = string_of_float f in
  let len = String.length str in
    if str.[0] = '-' then
      let factor2 = power_num_int num_ten (len - 3) in
      let z =
        if str.[1] = '1' then (* check whether str = "-1." *)
          num_one
        else
          num_of_string (String.sub str 3 (len - 3))
      in
        minus_num (div_num (mult_num z factor) factor2)
    else
      let factor2 = power_num_int num_ten (len - 2) in
      let z =
        if str.[0] = '1' then (* check whether str = "1." *)
          num_one
        else
          num_of_string (String.sub str 2 (len - 2))
      in
        div_num (mult_num z factor) factor2
  
let serialise_num output x =
  let n = Q.get_num x in
  let d = Q.get_den x in
  let s1 = Z.to_string_base ~base:16 n in
  let s2 = Z.to_string_base ~base:16 d in
  let l1 = String.length s1 in
  let l2 = String.length s2 in
  let b10 = l1 land 0xff in
  let b11 = (l1 lsr 8) land 0xff in
  let b12 = (l1 lsr 16) land 0xff in
  let b13 = (l1 lsr 24) land 0xff in
  let b20 = l2 land 0xff in
  let b21 = (l2 lsr 8) land 0xff in
  let b22 = (l2 lsr 16) land 0xff in
  let b23 = (l2 lsr 24) land 0xff in
    output (char_of_int b13);
    output (char_of_int b12);
    output (char_of_int b11);
    output (char_of_int b10);
    output (char_of_int b23);
    output (char_of_int b22);
    output (char_of_int b21);
    output (char_of_int b20);
    for i = 0 to String.length s1 - 1 do
      output s1.[i]
    done;
    for i = 0 to String.length s2 - 1 do
      output s2.[i]
    done
  
let unserialise_num input =
  let b13 = int_of_char (input ()) in
  let b12 = int_of_char (input ()) in
  let b11 = int_of_char (input ()) in
  let b10 = int_of_char (input ()) in
  let b23 = int_of_char (input ()) in
  let b22 = int_of_char (input ()) in
  let b21 = int_of_char (input ()) in
  let b20 = int_of_char (input ()) in
  let len1 = ((b10 lor (b11 lsl 8)) lor (b12 lsl 16)) lor (b13 lsr 24) in
  let len2 = ((b20 lor (b21 lsl 8)) lor (b22 lsl 16)) lor (b23 lsr 24) in
  let s1 = String.create len1 in
  let s2 = String.create len2 in
    for i = 0 to len1 - 1 do
      s1.[i] <- input ()
    done;
    for i = 0 to len2 - 1 do
      s2.[i] <- input ()
    done;
    let d = Z.from_string_base ~base:16 s1 in
    let n = Z.from_string_base ~base:16 s2 in
      Q.from_zs d n

(*-----------------------------------------------------------------------*)

let py_fail s =
  pyerr_clear ();
  failwith s

let py_module name =
  let m = pyimport_importmodule name in
    if m = pynull () then
      py_fail ("Failed to import Python module: " ^ name)
    else
      m

let py_module_call m function_name args =
  let dict = pymodule_getdict m in
  let func = pydict_getitemstring (dict, function_name) in
    pyeval_callobject (func, args)

let pythonize_num n =
  let gmpy = py_module "gmpy" in
    py_module_call gmpy "mpq" (pytuple_fromsingle (pybytes_fromstring (string_of_num n)))

let unpythonize_num py_n =
  let gmpy = py_module "gmpy" in
  let numer = pyint_asint (py_module_call gmpy "numer" (pytuple_fromsingle py_n)) in
  let denom = pyint_asint (py_module_call gmpy "denom" (pytuple_fromsingle py_n)) in
    num_of_ints numer denom

(*-----------------------------------------------------------------------*)
